package com.itany.maven.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@WebServlet(urlPatterns = "/sayHello")
public class HelloServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {




        String dirverClassName="com.mysql.jdbc.Driver";
        String url="jdbc:mysql://127.0.0.1:3306/maven?useUnicode=true&characterEncoding=utf8";
        String username="root";
        String password="";



        Connection con=null;
        PreparedStatement ps=null;

        try {
            Class.forName(dirverClassName);
            con= DriverManager.getConnection(url,username,password);
            con.setAutoCommit(false);

            String sql=new StringBuffer()
                    .append("insert into t_user ")
                    .append("    (username) ")
                    .append("values ")
                    .append("    (?) ")
                    .toString();

            ps=con.prepareStatement(sql);

            ps.setString(1,"abc");
            ps.executeUpdate();

            con.commit();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                con.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }

        } finally {
            if(ps!=null){
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(con!=null){
                try {
                    con.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }




        request.setAttribute("message","Hello");
        request.getRequestDispatcher("/hello.jsp").forward(request,response);
    }
}
